package com.roamer.school.repository.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Supplier;

/**
 * mybatis-plus公共字段自动处理器
 *
 * @author roamer
 * @version V1.0
 * @date 2019/1/15 13:53
 */
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    private static final Map<String, Supplier<?>> FIELD_MAP = new LinkedHashMap<>(4);

    static {
        FIELD_MAP.put("version", () -> 1L);
        FIELD_MAP.put("isDeleted", () -> Boolean.FALSE);
        FIELD_MAP.put("gmtCreate", Date::new);
        FIELD_MAP.put("gmtModified", Date::new);
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        if (log.isDebugEnabled()) {
            log.debug("MetaObjectHandler insert");
        }
        FIELD_MAP.forEach((k, v) -> {
            Object version = getFieldValByName(k, metaObject);
            if (Objects.isNull(version)) {
                setFieldValByName(k, v.get(), metaObject);
            }
        });
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (log.isDebugEnabled()) {
            log.debug("MetaObjectHandler update");
        }
        setFieldValByName("gmtModified", new Date(), metaObject);
    }
}
